package android.medicalcloud.com.yiapp.base.net;

import android.content.Context;
import android.medicalcloud.com.yiapp.base.exc.BaseException;
import android.medicalcloud.com.yiapp.base.net.lisener.HttpNetCallBack;
import android.medicalcloud.com.yiapp.base.net.lisener.NetCallback;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.MapUtils;
import android.medicalcloud.com.yiapp.yilian.utils.android.Common;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实现 httpclient 的manager
 */
public class HttpClientManager implements HttpNetCallBack {

    static AsyncHttpClient client;
    static Context context;

    public static HttpClientManager getInstance(Context con) {
        context = con;
        client = new AsyncHttpClient();
        return SingleClearCach.instance;

    }

    @Override
    public void get(String url, Map<String, Object> params, long timeOut, boolean cach, NetCallback responesCallBack) throws BaseException {
        client.setTimeout((int) timeOut);
        client.setConnectTimeout((int) timeOut);
        url = MapUtils.map2UrlParams(url, params);
        Map<String, String> header = new HashMap<String, String>();
        addHeader(header);
        Logger.e("--request=get=" + url);
        client.get(url, new ReslutCallBack(responesCallBack));
    }

    @Override
    public void getWithHeader(String url, Map<String, Object> params, Map<String, String> header, long timeOut, boolean cach, NetCallback responesCallBack) throws BaseException {
        client.setTimeout((int) timeOut);
        client.setConnectTimeout((int) timeOut);
        url = MapUtils.map2UrlParams(url, params);
        Logger.e("--request=get=" + url);
        addHeader(header);
        client.get(url, new ReslutCallBack(responesCallBack));
    }

    @Override
    public void post(String url, Map<String, Object> params, long timeOut, boolean cach, NetCallback responesCallBack) throws BaseException {
        client.setTimeout((int) timeOut);
        client.setConnectTimeout((int) timeOut);
        Logger.e("--request=post=" + url);
        Map<String, String> header = new HashMap<String, String>();
        addHeader(header);
        client.post(context, url, addParam(params), new ReslutCallBack(responesCallBack));

    }

    @Override
    public void postWithHeader(String url, Map<String, Object> params, Map<String, String> header, long timeOut, boolean cach, NetCallback responesCallBack) throws BaseException {
        client.setTimeout((int) timeOut);
        client.setConnectTimeout((int) timeOut);
        addHeader(header);
        Logger.e("--request=post=" + url);

        client.post(context, url, addParam(params), new ReslutCallBack(responesCallBack));
    }

    @Override
    public void cancle() {
        client.cancelRequests(context, true);
    }

    private void addHeader(Map<String, String> header) {
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                Logger.e("key=eeeee=" + entry.getKey());
                Logger.e("values=eeeee=" + entry.getValue());
                client.addHeader(entry.getKey(), entry.getValue());
            }
        }
        client.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        //client.addHeader("X-YY-TOKEN", "2383b1e56cd7660b8a57e2d606cc2c3b-1485935078-liuguijun");

    }

    private RequestParams addParam(Map<String, Object> param) {
        RequestParams params1 = new RequestParams();
        for (Map.Entry<String, ?> entry : param.entrySet()) {
            params1.add(entry.getKey(),entry.getValue().toString());
            if ("file".equals(entry.getKey())) {
                try {
                    if (entry.getValue() instanceof File)
                        params1.put("file", (File) entry.getValue());
                    if (entry.getValue() instanceof List){
                        List<File> files = (List<File>)entry.getValue();
                        File[] files1=new File[files.size()];
                        for (int i=0;i<files.size();i++){
                            files1[i]=files.get(i);
                        }
                        params1.put("file",files1);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return params1;
    }

    static class SingleClearCach {
        static HttpClientManager instance = new HttpClientManager();
    }

    public class ReslutCallBack extends AsyncHttpResponseHandler {

        NetCallback responesCallBack;

        public ReslutCallBack(NetCallback responesCallBack) {
            this.responesCallBack = responesCallBack;
        }

        @Override
        public void onStart() {
            super.onStart();
            responesCallBack.onstart();


        }

        @Override
        public void onSuccess(int i, Header[] headers, byte[] bytes) {

            try {
                String reslut = new String(bytes, "utf-8");
                responesCallBack.dealReslut(reslut);
                Logger.e("输出结果=" + reslut);

            } catch (Exception e) {
                Logger.e("转换异常");
            }
            responesCallBack.onEnd();


        }

        @Override
        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            Logger.e("网络请求失败");
            try {
                String s = new String(bytes, "UTF-8");
                Logger.e(s);
            } catch (Exception e) {
            }


            Logger.e(throwable.getLocalizedMessage());
            responesCallBack.onEnd();
            if (throwable instanceof SocketTimeoutException) {
                responesCallBack.dealFailer(new Exception("socket time out>>>error message:" + throwable.getLocalizedMessage()));
                return;
            }
            if (!Common.isNetworkAvailable()) {
                responesCallBack.dealFailer(new Exception("no network>>>error message:" + throwable.getLocalizedMessage()));
            }
            responesCallBack.dealFailer(new Exception("bad server>>>error message:" + throwable.getLocalizedMessage()));
        }
    }

}
